<!-- 产品列表 -->
<template>
    <div style="height: calc(100vh - 90px);display: flex;flex-direction: column;">

      <!-- body -->
      <div style="padding: 16px;flex: 1;overflow-y: auto;">
        <el-form :model="form" ref="form" :rules="rules" label-width="80px" :inline="false" size="normal">
          <el-form-item label="产品分类">
              <el-select v-model="form.productClassId" placeholder="请选择"
                @change="selectChanged(form.productClassId)">
                  <el-option
                  v-for="(item,idx) in kinds"
                  :key="idx"
                  :label="item.name"
                  :value="item.id">
                  </el-option>
              </el-select>
          </el-form-item>
          
          <el-form-item label="产品名称">
              <el-input placeholder="请输入产品名称" v-model="form.productName"></el-input>
          </el-form-item>

          <el-form-item label="产品图标" style="position: relative;">

            <div 
            v-if="form.productImg.length > 0"
            style="position: relative;width: 130px;height: 130px;">
                <el-image :src="form.productImg" fit="fill" :lazy="true" 
                style="width: 130px;height: 130px;"
                ></el-image>
                <i class="el-icon-error" style="font-size: 24px;color: red;position: absolute;
                top: 0;right: 0;cursor: pointer;
                " @click="form.productImg = ''"></i>
            </div>
            <el-upload
            v-if="form.productImg.length == 0"
            action="http://47.103.2.155:8801/api/File/upload"
            list-type="picture-card"
            name="file"
            :on-success="uploadSuccess"
            :limit="1"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
            <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>

          <el-form-item label="是否展示">
            <el-switch v-model="iswitch"></el-switch>
          </el-form-item>
          <el-form-item label="产品介绍">
            <TinyEditor ref="ue" :content="form.productdis"/>
          </el-form-item>
          <el-form-item label="文本选项类型名称" v-for="(item,idx) in inputs" :key="idx" size="mini" label-width="100px">
              <div>{{item.label}}标题</div>
              <el-input placeholder="请输入选项名称" size="small" v-model="item.name"></el-input>
              <div v-if="item.type == 'more' || item.type == 'one'">
                <div>选项值</div>
                <el-input placeholder="请输入选项内容" size="small" v-model="item.value"></el-input>
              </div>

              <div v-if="item.type == 'img'">
                <div>最大图片数量</div>
                <el-input placeholder="请输入最大图片数量" size="small" v-model="item.value"></el-input>
              </div>

              <div v-if="item.type == 'colorCard'">
                <div>图片上传</div>
                <el-upload
                  action="http://47.103.2.155:8801/api/File/upload"
                  list-type="picture-card"
                  name="file"
                  :on-success="(res,file, fileList) => uploadSuccessColorCard(res, file, fileList, item)"
                  :limit="6"
                  :file-list="item.picList"
                  :on-remove="(file, fileList) => handleRemoveColorCard(file, fileList, item)"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
              </div>

              <div style="font-size: 13px;color: #666666;">{{item.desc}}</div>
              <el-button @click.native="inputs.splice(idx,1)" type="danger" size="mini" style="margin-top: 5px;">删除</el-button>
          </el-form-item>

          <div style="height: 1px;background-color: #ebebeb;margin: 12px 0;"></div>
          
          <el-form-item label="图片选项类型名称" v-for="(item,idx) in imgs" :key="idx" size="mini" label-width="100px">
              <div>{{item.label}}标题</div>
              <el-input placeholder="请输入选项名称" size="small" v-model="item.name"></el-input>
              <div>
                <div>最大图片数量</div>
                <el-input placeholder="请输入最大图片数量" size="small" v-model="item.max"></el-input>
              </div>
              <div style="font-size: 13px;color: #666666;">{{item.desc}}</div>
              <el-button @click.native="imgs.splice(idx,1)" type="danger" size="mini" style="margin-top: 5px;">删除</el-button>
          </el-form-item>


          <el-form-item label="自定义标题" label-width="100px">
              <el-button type="primary" @click="showType = true;" size="mini">添加选项</el-button>
          </el-form-item>


            

        </el-form>
      </div>

      <!-- button -->
      <div style="display: flex;justify-content: center;">
        <el-button type="primary" size="small" style="width: 15%;" @click.native="doneHandle">提交</el-button>
      </div>
    

      <!-- dialog -->
      <el-dialog
        title="请选择类型"
        :visible.sync="showType"
        width="40%"
        @close="">
            <el-button type="danger" @click.native="addOptionHandle('img')" plain size="medium">图片</el-button>
            <el-button type="primary" @click.native="addOptionHandle('text')" plain size="medium">文本</el-button>
            <el-button type="success" @click.native="addOptionHandle('more')" plain size="medium">多选</el-button>
            <el-button type="warning" @click.native="addOptionHandle('one')" plain size="medium">单选</el-button>
            <el-button type="info" @click.native="addOptionHandle('colorCard')" plain size="medium">色卡</el-button>
        <span slot="footer">
          <el-button @click="showType=false">取消</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import CateTable from './cate_table.vue'
  import AddCom from "./cate_add.vue"
  import EditCom from "./cate_edit.vue"
  import Api from "./api"
  import TinyEditor from '@/components/Tinyce';
  
  export default {
    components: {
      CateTable,
      AddCom,
      EditCom,
      TinyEditor
    },
    data() {
      return {
        showType:false,
        iswitch:false,

        activeName: 'first',
        name: '我要下单',
        openAdd:false,
        openEdit:false,
        items:[],
        currentData:{},
        inputs:[],
        imgs:[],
        form:{
            classId:undefined,
            isShow:0,
            serviceName:undefined,
            inputJson:'',
            imgJson:'',
            productImg:'',///封面
            productdis: ''
        },
        kinds:[],
        ueEditorJson: undefined
      }
    },
    mounted() {
        this.netKindList();
    },
  
    methods:{
      async netKindList() {
        var res = await Api.YzKindGetList({});
        this.kinds = res.data.data;

        this.form = this.$route.params;
        const list = JSON.parse(this.form.inputJson);
        this.inputs = list.map(item => {
          if (item.type === 'colorCard') {
            const currList = this.initColorCardList(item.value);
            return { ...item, picList: currList }
          }
          return { ...item }
        })
        this.imgs = JSON.parse(this.form.imgJson);
        this.iswitch = this.form.isShow == 1;

        for (const item of this.kinds) {
            if(item.name == this.form.productClassName) {
                this.form.productClassId = item.id;
                break;
            }
        }
      },
  
      addOptionHandle(type){
        if (type == 'img') {
          let item = {
            label:"图片",
            desc:"请设置图片数量",
            type:'img',
          };
          this.imgs.push(item);
        } else {
          this.showType = false;
          let labelDict = {'text':"文本",'more':'多选','one':'单选', 'colorCard': '色卡'};
          let desDict = {
            'text':"",
            'more':'如 问题故障类型，选项可以多个内容，用逗号，分隔',
            'one':'如 需要登高设备，选项: 需要师傅携带登高设备,不需要师傅携带登高设备，多个选项内容，用逗号，分隔',
            'colorCard': ''
          };
          const picList = type == 'colorCard' ? { picList: [] } : {}
          let item = {
            label: labelDict[type],
            desc: desDict[type],
            type: type,
            ...picList
          };
          this.inputs.push(item);
        }
        this.showType = false
      },



      editHandle({data}) {
        this.currentData = data;
        this.openEdit = true;
      },

      async doneHandle(){
        this.form.isShow = this.iswitch ? 1 : 0;
        if (this.form.productClassId == undefined) {
          this.$message({
            message: '请选择类型',
            type: 'error',
            showClose: true,
            duration: 3000,
          });
          
          return
        }
        if (this.form.productName == undefined) {
          this.$message({
            message: '请输入产品名称',
            type: 'error',
            showClose: true,
            duration: 3000,
          });
          return
        }

        let self = this;
        const inputList = this.handleColorCardList(this.inputs);
        this.form.inputJson = JSON.stringify(inputList);
        this.form.imgJson = JSON.stringify(this.imgs);
        this.form.productdis = this.$refs.ue.content;
        // console.log('form', this.form)
        let res = await Api.netYzProductUpdate(this.form);
        let data = res.data;
        if (data.status == 200) {
          this.$message({
            message: '操作成功',
            type: 'success',
            showClose: true,
            duration: 3000,
            onClose:()=>{
                this.$store.dispatch("tagsView/delView", this.$route);
                this.$router.replace({name:'goods'});
            }
          });
        } else {
          this.$message({
            message: data.msg,
            type: 'error',
            showClose: true,
            duration: 3000,
          });
        }
      },

      uploadSuccess(obj,res,file) {
        if (obj.code == 200) {
          this.$message.success({dangerouslyUseHTMLString: true,
            message: obj.msg})
          let {fileUrl} = obj.data;
          this.form.productImg = fileUrl;
        } else {
          this.$message.error('操作失败')
        }
      },

      uploadSuccessColorCard(obj, res, fileList, records) {
        if (obj.code == 200) {
          this.$message.success({dangerouslyUseHTMLString: true, message: obj.msg})
          records.picList = fileList;
        } else {
          this.$message.error('操作失败')
        }
      },

      handleRemoveColorCard(file, fileList, records) {
        records.picList = fileList;
      },

      handleColorCardList(list) {
        const inputList = Array.isArray(list) ? list.map(item => {
          if (item.type === 'colorCard') {
            const picList = item.picList || [];
            const currList = picList.map(item => {
              if (item.response) {
                return item.response.data.fileUrl;
              }
              return item.url
            })
            item.value = currList.length ? currList.join(',') : ''
            delete item.picList;
          }
          return { ...item }
        }) : [];
        return inputList
      },

      initColorCardList(str) {
        let currList = [];
        if (str && typeof str === 'string') {
          const list = str.split(',');
          if (list.length) {
            currList = list.map((item, index) => {
              return { name: `图${index}`, url: item }
            })
          }
        }
        return currList;
      },

      selectChanged(id) {
        for (const item of this.kinds) {
          if(id == item.id) {
            this.form.productClassName = item.name;
            this.form.productClassId = item.id;
            break;
          }
        }
      },
    },
  }
  </script>
  
  <style>
  .deleteBorder .el-tabs__nav-wrap::after{
      height: 0;
    }
  </style>
  